package com.ced.sip.purchase.askPrice.action.epp;

import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;



import com.ced.base.action.BaseAction;
import com.ced.base.exception.BaseException;
import com.ced.sip.common.BaseDataInfosUtil;
import com.ced.sip.common.DictStatus;
import com.ced.sip.common.TableStatus;
import com.ced.sip.common.UserRightInfoUtil;
import com.ced.sip.common.biz.IPurchaseRecordLogBiz;
import com.ced.sip.common.entity.PurchaseRecordLog;
import com.ced.sip.common.utils.DateUtil;
import com.ced.sip.common.utils.RandomColor;
import com.ced.sip.common.utils.StringUtil;
import com.ced.sip.common.utils.encrypt.Base64;
import com.ced.sip.common.utils.encrypt.RSAEncrypt;
import com.ced.sip.purchase.askPrice.biz.IAskBidListBiz;
import com.ced.sip.purchase.askPrice.entity.AskBidList;
import com.ced.sip.purchase.askPrice.util.AskProgressStatus;
import com.ced.sip.purchase.base.biz.IBidBusinessResponseBiz;
import com.ced.sip.purchase.base.biz.IBidNegotiateBiz;
import com.ced.sip.purchase.base.biz.IBidPriceBiz;
import com.ced.sip.purchase.base.biz.IBidPriceDetailBiz;
import com.ced.sip.purchase.base.biz.IBidPriceDetailHistoryBiz;
import com.ced.sip.purchase.base.biz.IBidPriceHistoryBiz;
import com.ced.sip.purchase.base.biz.IBidProcessLogBiz;
import com.ced.sip.purchase.base.biz.IInviteSupplierBiz;
import com.ced.sip.purchase.base.biz.IRequiredCollectBiz;
import com.ced.sip.purchase.base.entity.BidBusinessResponse;
import com.ced.sip.purchase.base.entity.BidNegotiate;
import com.ced.sip.purchase.base.entity.BidPrice;
import com.ced.sip.purchase.base.entity.BidPriceDetail;
import com.ced.sip.purchase.base.entity.BidPriceDetailHistory;
import com.ced.sip.purchase.base.entity.BidPriceHistory;
import com.ced.sip.purchase.base.entity.BidProcessLog;
import com.ced.sip.purchase.base.entity.InviteSupplier;
import com.ced.sip.purchase.base.entity.RequiredCollect;
import com.ced.sip.purchase.base.entity.RequiredCollectDetail;
/** 
 * 类名称：BidPriceAction
 * 创建人：luguanglei 
 * 创建时间：2017-04-25
 */
public class AskBidPriceResponseAction extends BaseAction {
    //项目信息服务类
    private IRequiredCollectBiz iRequiredCollectBiz;
	//邀请供应商
	private IInviteSupplierBiz iInviteSupplierBiz;
    //询价基本信息
	private IAskBidListBiz iAskBidListBiz;
	// 供应商报价信息 
	private IBidPriceBiz iBidPriceBiz;
	// 供应商报价明细信息 
	private IBidPriceDetailBiz iBidPriceDetailBiz;
	// 供应商历史报价信息 
	private IBidPriceHistoryBiz iBidPriceHistoryBiz;
	// 供应商历史报价明细信息 
	private IBidPriceDetailHistoryBiz iBidPriceDetailHistoryBiz;
	// 供应商商务响应 
	private IBidBusinessResponseBiz iBidBusinessResponseBiz;
	 //项目日志记录服务类
	 private IPurchaseRecordLogBiz iPurchaseRecordLogBiz;
	 //标段流程记录实例表
	 private IBidProcessLogBiz iBidProcessLogBiz;
	 // 磋商信息服务类
	 private IBidNegotiateBiz iBidNegotiateBiz;
	 
		
	// 供应商报价信息
	private BidPrice bidPrice;
	// 供应商报价信息明细
	private BidPriceDetail bidPriceDetail;
	// 供应商报价历史信息
	private BidPriceHistory bidPriceHistory;
	// 供应商报价历史明细信息
	private BidPriceDetailHistory bidPriceDetailHistory;
	// 商务响应项信息
	private BidBusinessResponse bidBusinessResponse;
	
	private InviteSupplier inviteSupplier;
	
	private AskBidList askBidList;
	
	private RequiredCollectDetail requiredCollectDetail;
	
	private BidNegotiate bidNegotiate;
	
	private Long rcId;
    private String isDetail;

    private RequiredCollect requiredCollect;
    private PurchaseRecordLog purchaseRecordLog;
 	private BidProcessLog bidProcessLog;
 	
	/**
 	* 当流程监控执行关键节点时候需要更新标段监控表，同时更新当前节点的完成时间，插入下一个节点的接收时间
 	* @param rcId 项目id
 	* @param currProgress_Status 当前节点
 	* @param nextProgress_Status 下一个节点
 	* @param nextProgress_Status_Text 下一个节点的节点名称
 	* @author luguanglei
 	* @throws BaseException 
 	*/
 	private void updateBidMonitorAndBidProcessLog(Long rcId,Long currProgress_Status, Long nextProgress_Status,String nextProgress_Status_Text)throws BaseException{
 		//修改项目监控至下一个节点
 		requiredCollect=new RequiredCollect();
 		requiredCollect.setRcId(rcId);
 		requiredCollect=this.iRequiredCollectBiz.getRequiredCollect(rcId);
 	    if(requiredCollect.getServiceStatus()<nextProgress_Status){
 	    	requiredCollect.setServiceStatus(nextProgress_Status);
 	    	requiredCollect.setServiceStatusCn(nextProgress_Status_Text);
 	        this.iRequiredCollectBiz.updateRequiredCollect(requiredCollect);
 	    }
 	  //修改项目日志表的当前节点的完成时间
 	    bidProcessLog=new BidProcessLog();
 	    bidProcessLog.setRcId(rcId);
 	    bidProcessLog.setBidNode(currProgress_Status);
 	    bidProcessLog=this.iBidProcessLogBiz.getBidProcessLogByRcIdAndBidNode(bidProcessLog);
 	    bidProcessLog.setCompleteDate(DateUtil.getCurrentDateTime());
 	    this.iBidProcessLogBiz.updateBidProcessLog(bidProcessLog);
 	  //新增项目日志表的下一个节点的接收时间
 	    bidProcessLog=new BidProcessLog();
 	    bidProcessLog.setRcId(rcId);
 	    bidProcessLog.setBidNode(nextProgress_Status);
 	    bidProcessLog=this.iBidProcessLogBiz.getBidProcessLogByRcIdAndBidNode(bidProcessLog);
 	    if(bidProcessLog.getBplId()==null){
 	    bidProcessLog.setReceiveDate(DateUtil.getCurrentDateTime());
 	    this.iBidProcessLogBiz.saveBidProcessLog(bidProcessLog);
 	    }
 	
 	}
 	/**
	 * 判断是否是编制人员
	 * @param bidMonitor
	 * @return
	 */
 	private  boolean isWriter(String writer){
		boolean isWriter=false;
		String username=UserRightInfoUtil.getUserName(this.getRequest());
		//当前登录人是不是编制人员
		if(username.equals(writer)) isWriter=true;
		return isWriter;
	}
	
	/**
	 * 比价磋商信息列表项目监控
	 * @return
	 * @throws BaseException 
	 * @Action
	 */
	public String viewAskBidPriceResponseMonitor() throws BaseException {
		String view="askBidPriceResponseMonitorDetail";
		try{

			requiredCollect=this.iRequiredCollectBiz.getRequiredCollect(rcId);
			
			if(!isWriter(requiredCollect.getWriter())) isDetail="detail";
			
			String supplierName="";
			bidPrice=new BidPrice();
			bidPrice.setRcId(rcId);
			List<BidPrice> bpList=new ArrayList<BidPrice>();
			List<BidNegotiate> bnList=null;
			String isResponseNegotiate="2"; //默认没有磋商信息
			List<Object[]> objectList=this.iBidPriceBiz.getBidPriceListSupplierName(bidPrice);
			for(Object[] object:objectList){
				isResponseNegotiate="2"; 
				bidPrice=(BidPrice)object[0];
				
				//查询磋商信息
				bidNegotiate=new BidNegotiate();
				bidNegotiate.setRcId(rcId);
				bidNegotiate.setSupplierId(bidPrice.getSupplierId());
				bnList=this.iBidNegotiateBiz.getBidNegotiateListByBidNegotiate(bidNegotiate);
				for(BidNegotiate bidNegotiate:bnList){
					isResponseNegotiate="1";
					if(StringUtil.isBlank(bidNegotiate.getResponseNegotiate())) {
						isResponseNegotiate="0";
						 break;
					}
				}
				bidPrice.setIsResponseNegotiate(isResponseNegotiate);
				
				supplierName=(String)object[1];
				bidPrice.setSupplierName(supplierName);
				bpList.add(bidPrice);
			}
			this.setListValue(bpList);
			
			askBidList=this.iAskBidListBiz.getAskBidListByRcId(rcId);
 			boolean isEcryptionTime=false;
 			//判断当时时间是否大于报价解密时间
 	        Calendar calendar = Calendar.getInstance(Locale.CHINA);
 	        Date date = calendar.getTime();
 	        if(askBidList.getReturnDate()!=null){
 			if(date.getTime()>=askBidList.getDecryptionDate().getTime()){
 				isEcryptionTime=true;
 			}}
 	        this.getRequest().setAttribute("isEcryptionTime", isEcryptionTime);
 	        this.getRequest().setAttribute("askBidList", askBidList);
 	        
			//公告未发布 且项目状态为正常 且非查看页面
            if(TableStatus.BID_STATUS_1.equals(requiredCollect.getBidStatus())&&AskProgressStatus.Progress_Status_25==requiredCollect.getServiceStatus()&&StringUtil.isBlank(isDetail))
			//if(true)
			{  
               
    	        view="askBidPriceResponseMonitorUpdate";
			}	
		   } catch (Exception e) {
			log.error("比价磋商信息列表错误！", e);
			throw new BaseException("比价磋商信息列表错误！", e);
		}		
		return view;		
	}
	/**
	 * 比价磋商执行下一步
	 * @return
	 * @throws BaseException 
	 */
	public String updateAskBidPriceResponseMonitor() throws BaseException {
		String view="success";
		try{
			Long rcId=Long.parseLong(this.getRequest().getParameter("rcId"));
			
			//磋商没有完成的将不能再磋商
			bidNegotiate=new BidNegotiate();
			bidNegotiate.setRcId(rcId);
			List<BidNegotiate> list=this.iBidNegotiateBiz.getBidNegotiateListByBidNegotiate(bidNegotiate);
			for(BidNegotiate bidNegotiate:list){
				bidNegotiate.setStatus(TableStatus.COMMON_0);
				this.iBidNegotiateBiz.updateBidNegotiate(bidNegotiate);
			}
			
			updateBidMonitorAndBidProcessLog(rcId, AskProgressStatus.Progress_Status_25, AskProgressStatus.Progress_Status_26, AskProgressStatus.Progress_Status_26_Text);
	       	
			//保存流程跟踪信息
			purchaseRecordLog = new PurchaseRecordLog();
			purchaseRecordLog.setOperateDate(DateUtil.getCurrentDateTime());
			purchaseRecordLog.setOperatorId(UserRightInfoUtil.getUserId(this.getRequest())+"");
			purchaseRecordLog.setOperatorName(UserRightInfoUtil.getUserName(this.getRequest()));
			purchaseRecordLog.setRcId(rcId);
			purchaseRecordLog.setOperateContent("比价磋商执行下一步");
			purchaseRecordLog.setBidNode(AskProgressStatus.Progress_Status_26_Text);
			this.iPurchaseRecordLogBiz.savePurchaseRecordLog(purchaseRecordLog);
			
			this.getRequest().setAttribute("message","操作成功");
			this.getRequest().setAttribute("operModule", "比价磋商执行下一步成功");
		} catch (Exception e) {
			log("比价磋商执行下一步错误！", e);
			throw new BaseException("比价磋商执行下一步错误！", e);
		}
		return view;
		
	}
	/**
	 * 解密报价信息
	 * @return
	 * @throws BaseException
	 */
	public void decryptPrice() throws BaseException{
		String result="解密失败";
		PrintWriter out= null;
		try{ 
			Long comId=UserRightInfoUtil.getComId(this.getRequest());
			out = getResponse().getWriter(); 
			String privateKey;
			byte[] res;
			Double price;
			List<BidPrice> bpList;
			List<BidPriceDetail> bpdList;
			List<BidPriceHistory> bphList;
			List<BidPriceDetailHistory> bpdhList;
			
			inviteSupplier=new InviteSupplier();
			inviteSupplier.setRcId(rcId);
			List<InviteSupplier> isList=this.iInviteSupplierBiz.getInviteSupplierList(inviteSupplier);
			for(InviteSupplier inviteSupplier:isList){
				//得到私钥
				privateKey=inviteSupplier.getPrivateKey();
				
				//解密报价
				bidPrice=new BidPrice();
				bidPrice.setRcId(rcId);
				bidPrice.setSupplierId(inviteSupplier.getSupplierId());
				bpList=this.iBidPriceBiz.getBidPriceListForDecrypt(bidPrice);
				for(BidPrice bidPrice:bpList){
					res=RSAEncrypt.decrypt(RSAEncrypt.loadPrivateKeyByStr(privateKey), Base64.decode(bidPrice.getEncryTotalPrice()));
					price=Double.parseDouble(new String(res));	
					bidPrice.setTotalPrice(price);
					this.iBidPriceBiz.updateBidPrice(bidPrice);
					
					bidPriceDetail=new BidPriceDetail();
					bidPriceDetail.setBpId(bidPrice.getBpId());
					bpdList=this.iBidPriceDetailBiz.getBidPriceDetailList(bidPriceDetail);
					for(BidPriceDetail bidPriceDetail:bpdList){
						res=RSAEncrypt.decrypt(RSAEncrypt.loadPrivateKeyByStr(privateKey), Base64.decode(bidPriceDetail.getEncryPrice()));
						price=Double.parseDouble(new String(res));	
						bidPriceDetail.setPrice(price);
						this.iBidPriceDetailBiz.updateBidPriceDetail(bidPriceDetail);
						
					}
				}
				
				//解密历史报价信息
				bidPriceHistory=new BidPriceHistory();
				bidPriceHistory.setSupplierId(inviteSupplier.getSupplierId());
				bidPriceHistory.setRcId(rcId);
				bphList=this.iBidPriceHistoryBiz.getBidPriceHistoryListForDecrypt(bidPriceHistory);
				for(BidPriceHistory bidPriceHistory:bphList){
					res=RSAEncrypt.decrypt(RSAEncrypt.loadPrivateKeyByStr(privateKey), Base64.decode(bidPriceHistory.getEncryTotalPrice()));
					price=Double.parseDouble(new String(res));	
					bidPriceHistory.setTotalPrice(price);
					this.iBidPriceHistoryBiz.updateBidPriceHistory(bidPriceHistory);
					
					bidPriceDetailHistory=new BidPriceDetailHistory();
					bidPriceDetailHistory.setBphId(bidPriceHistory.getBphId());
					bpdhList=this.iBidPriceDetailHistoryBiz.getBidPriceDetailHistoryList(bidPriceDetailHistory);
					for(BidPriceDetailHistory bidPriceDetailHistory:bpdhList){
						res=RSAEncrypt.decrypt(RSAEncrypt.loadPrivateKeyByStr(privateKey), Base64.decode(bidPriceDetailHistory.getEncryPrice()));
						price=Double.parseDouble(new String(res));	
						bidPriceDetailHistory.setPrice(price);
						this.iBidPriceDetailHistoryBiz.updateBidPriceDetailHistory(bidPriceDetailHistory);
					}
				}
			}
			askBidList=this.iAskBidListBiz.getAskBidListByRcId(rcId);
			askBidList.setPriceStatus(TableStatus.PRICE_STATUS_02);
			this.iAskBidListBiz.updateAskBidList(askBidList);
			result="解密成功"; 
			this.getRequest().setAttribute("operModule", "解密报价信息");
			this.getRequest().setAttribute("message", result);
			out.print(result);  
		} catch (Exception e) {
			log.error("解密报价信息错误！", e);
			out.print(result); 
		}
	}
	/**
	 * 查看供应商报价信息明细信息
	 * @return
	 * @throws BaseException 
	 */
	public String viewAskBidPriceResponeDetail() throws BaseException {
		
		try{		      			
            bidPrice=this.iBidPriceBiz.getBidPrice(bidPrice.getBpId() );
			
			askBidList=this.iAskBidListBiz.getAskBidListByRcId(bidPrice.getRcId());
            askBidList.setPriceTypeCn(BaseDataInfosUtil.convertDictCodeToName(askBidList.getPriceType(),DictStatus.COMMON_DICT_TYPE_1702));
		    askBidList.setPriceColumnTypeCn(BaseDataInfosUtil.convertDictCodeToName(askBidList.getPriceType(),DictStatus.COMMON_DICT_TYPE_1703));
			
		    List<BidPriceDetail> bpdList=new ArrayList<BidPriceDetail>();
			bidPriceDetail=new BidPriceDetail();
			bidPriceDetail.setBpId(bidPrice.getBpId());
			List<Object[]> objectList=this.iBidPriceDetailBiz.getBidPriceDetailListRequiredCollectDetail(bidPriceDetail);
			for(Object[] object:objectList){
				bidPriceDetail=(BidPriceDetail)object[0];
				requiredCollectDetail=(RequiredCollectDetail)object[1];
				bidPriceDetail.setRequiredCollectDetail(requiredCollectDetail);
				bpdList.add(bidPriceDetail);
			}
				
				
			bidBusinessResponse=new BidBusinessResponse();
			bidBusinessResponse.setBpId(bidPrice.getBpId());
			List<BidBusinessResponse> bbrList=this.iBidBusinessResponseBiz.getBidBusinessResponseList(bidBusinessResponse);
			
			this.getRequest().setAttribute("bidPrice", bidPrice);			
			this.getRequest().setAttribute("bpdList", bpdList);			
			this.getRequest().setAttribute("bbrList", bbrList);			
			this.getRequest().setAttribute("askBidList", askBidList);
			  
		} catch (Exception e) {
			log("查看供应商报价信息明细信息错误！", e);
			throw new BaseException("查看供应商报价信息明细信息错误！", e);
		}
		return DETAIL;
		
	}
	/**
	 * 供应商比价
	 * @return
	 * @throws BaseException 
	 */
	public String viewParityPrice() throws BaseException {
		
		try{	
			askBidList=this.iAskBidListBiz.getAskBidListByRcId(rcId);
            askBidList.setPriceTypeCn(BaseDataInfosUtil.convertDictCodeToName(askBidList.getPriceType(),DictStatus.COMMON_DICT_TYPE_1702));
		    askBidList.setPriceColumnTypeCn(BaseDataInfosUtil.convertDictCodeToName(askBidList.getPriceType(),DictStatus.COMMON_DICT_TYPE_1703));
			
		    
			bidPrice=new BidPrice();
			bidPrice.setRcId(rcId);
			List<Object[]> objectList=this.iBidPriceBiz.getBidPriceListSupplierName(bidPrice);
			String[] supplierStr=new String[objectList.size()];
			Long[] bpIdStr=new Long[objectList.size()];
			Double[] totalPriceStr=new Double[objectList.size()];
			Double[] taxRateStr=new Double[objectList.size()];
			String[] colorStr=new String[objectList.size()];
			int i=0;
			for(Object[] object:objectList){
				bidPrice=(BidPrice)object[0];
				supplierStr[i]=(String)object[1];
				bpIdStr[i]=bidPrice.getBpId();
				totalPriceStr[i]=bidPrice.getTotalPrice();
				taxRateStr[i]=bidPrice.getTaxRate()==null?Double.parseDouble("0"):bidPrice.getTaxRate();
				colorStr[i]=RandomColor.generateColor(i);
				i++;
			}
			
			List bidPriceList=this.iBidPriceDetailBiz.getBidPriceDetailListForParityPrice(bpIdStr, rcId);

			List bbrfList=this.iBidBusinessResponseBiz.getBidBusinessResponseForParityPrice(bpIdStr, rcId);
			
						
			this.getRequest().setAttribute("supplierStr", supplierStr);
			this.getRequest().setAttribute("bpIdStr", bpIdStr);
			this.getRequest().setAttribute("totalPriceStr", totalPriceStr);
			this.getRequest().setAttribute("colorStr", colorStr);
			this.getRequest().setAttribute("taxRateStr", taxRateStr);
			this.getRequest().setAttribute("bidPriceList", bidPriceList);
			this.getRequest().setAttribute("bbrfList", bbrfList);	
			this.getRequest().setAttribute("askBidList", askBidList);
		} catch (Exception e) {
			log("供应商比价信息错误！", e);
			throw new BaseException("供应商比价信息错误！", e);
		}
		return "parityPrice";
	}
	
	public IBidPriceBiz getiBidPriceBiz() {
		return iBidPriceBiz;
	}

	public void setiBidPriceBiz(IBidPriceBiz iBidPriceBiz) {
		this.iBidPriceBiz = iBidPriceBiz;
	}
	public IAskBidListBiz getiAskBidListBiz() {
		return iAskBidListBiz;
	}

	public void setiAskBidListBiz(IAskBidListBiz iAskBidListBiz) {
		this.iAskBidListBiz = iAskBidListBiz;
	}

	public IBidPriceDetailBiz getiBidPriceDetailBiz() {
		return iBidPriceDetailBiz;
	}

	public void setiBidPriceDetailBiz(IBidPriceDetailBiz iBidPriceDetailBiz) {
		this.iBidPriceDetailBiz = iBidPriceDetailBiz;
	}

	public IBidPriceHistoryBiz getiBidPriceHistoryBiz() {
		return iBidPriceHistoryBiz;
	}

	public void setiBidPriceHistoryBiz(IBidPriceHistoryBiz iBidPriceHistoryBiz) {
		this.iBidPriceHistoryBiz = iBidPriceHistoryBiz;
	}

	public IBidPriceDetailHistoryBiz getiBidPriceDetailHistoryBiz() {
		return iBidPriceDetailHistoryBiz;
	}

	public void setiBidPriceDetailHistoryBiz(
			IBidPriceDetailHistoryBiz iBidPriceDetailHistoryBiz) {
		this.iBidPriceDetailHistoryBiz = iBidPriceDetailHistoryBiz;
	}

	public IBidBusinessResponseBiz getiBidBusinessResponseBiz() {
		return iBidBusinessResponseBiz;
	}

	public void setiBidBusinessResponseBiz(
			IBidBusinessResponseBiz iBidBusinessResponseBiz) {
		this.iBidBusinessResponseBiz = iBidBusinessResponseBiz;
	}

	public Long getRcId() {
		return rcId;
	}

	public void setRcId(Long rcId) {
		this.rcId = rcId;
	}

	public IInviteSupplierBiz getiInviteSupplierBiz() {
		return iInviteSupplierBiz;
	}

	public void setiInviteSupplierBiz(IInviteSupplierBiz iInviteSupplierBiz) {
		this.iInviteSupplierBiz = iInviteSupplierBiz;
	}
	public IRequiredCollectBiz getiRequiredCollectBiz() {
		return iRequiredCollectBiz;
	}
	public void setiRequiredCollectBiz(IRequiredCollectBiz iRequiredCollectBiz) {
		this.iRequiredCollectBiz = iRequiredCollectBiz;
	}
	public IPurchaseRecordLogBiz getiPurchaseRecordLogBiz() {
		return iPurchaseRecordLogBiz;
	}
	public void setiPurchaseRecordLogBiz(IPurchaseRecordLogBiz iPurchaseRecordLogBiz) {
		this.iPurchaseRecordLogBiz = iPurchaseRecordLogBiz;
	}
	public IBidProcessLogBiz getiBidProcessLogBiz() {
		return iBidProcessLogBiz;
	}
	public void setiBidProcessLogBiz(IBidProcessLogBiz iBidProcessLogBiz) {
		this.iBidProcessLogBiz = iBidProcessLogBiz;
	}
	public String getIsDetail() {
		return isDetail;
	}
	public void setIsDetail(String isDetail) {
		this.isDetail = isDetail;
	}
	public BidPrice getBidPrice() {
		return bidPrice;
	}
	public void setBidPrice(BidPrice bidPrice) {
		this.bidPrice = bidPrice;
	}
	public IBidNegotiateBiz getiBidNegotiateBiz() {
		return iBidNegotiateBiz;
	}
	public void setiBidNegotiateBiz(IBidNegotiateBiz iBidNegotiateBiz) {
		this.iBidNegotiateBiz = iBidNegotiateBiz;
	}	
}
